<?php
// ------------------------------------------------------------------------------------
// Bestand:       DataBase
// Versie:        4.0
// Projekt:       Cursus MasterClass van Eduvision
// Datum:         14-07-2008
// Auteur(s):     Ronald Obbens
// Email(s):      ronaldobbens@gmail.com
// Revisie(s):	  4.0 - returns a DBoutput object
//
// Beschrijving:  The DataBase class executes querys on the database and returns the output
// ------------------------------------------------------------------------------------
//

require_once('LogWriter.php');
require_once('iDB.php');
require_once('DBoutput.php');


class DataBase implements iDB
{
	protected static $_instance;	
	
	private $m_sServer;
	private $m_sDatabase;
	private $m_sUsername;
	private $m_sPassword;
	private $m_aRecords;
	private $m_sConnection;
	private $m_oLog;
	
	
	public static function getInstance()
	{
		if (is_null(self::$_instance)) 
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}
		
	/**
	 * initiate database connection
	 *
	 */
	private function initDB()
	{
		$this->m_sConnection = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD);
		if($this->m_sConnection  === FALSE){ throw new Exception('No connection can be made with the database, ' . mysql_error($this->m_sConnection));}
		
		$bool = mysql_select_db(DB_DATABASE,$this->m_sConnection);
		if($bool === FALSE){ throw new Exception('The database cannot be opened/found, ' . mysql_error($this->m_sConnection));}
	} 
	
	/**
	 * get a DBoutput
	 *
	 * @param string $p_sQuery
	 * @return DBoutput
	 */
	public function runQuery($p_sQuery)
	{
		
		$output = new DBoutput();
		
		try
		{
			$this->initDB();
			$this->m_aRecords = mysql_query($p_sQuery,$this->m_sConnection) or die(mysql_error($this->m_sConnection));
			if($this->m_aRecords === FALSE){ throw new Exception('The query returns a foult, ' . mysql_error($this->m_sConnection));}
		}
		catch(Exception $e)
		{
			$output->setMessage($e->getMessage());			
		}
		
		//make the output
		$output->setRecordId(mysql_insert_id($this->m_sConnection));
		
		mysql_close($this->m_sConnection);
		
		$this->m_aRecords = mysql_fetch_array($this->m_aRecords);
	
		$output->addData($this->m_aRecords[0]);
		
		return $output;
	}
	
	public function runDirectQuery($p_sQuery){
		
		$output = new DBoutput();
		
		try
		{
			$this->initDB();
			
			$this->m_aRecords = mysql_query($p_sQuery,$this->m_sConnection) or die(mysql_error($this->m_sConnection));
			
			if($this->m_aRecords === FALSE){ throw new Exception('The query returns a foult, ' . mysql_error($this->m_sConnection));}
		}
		catch(Exception $e)
		{
			$output->setMessage($e->getMessage());			
		}
		
		$output->setRecordId(mysql_insert_id($this->m_sConnection));
		mysql_close($this->m_sConnection);
		
		while($record = mysql_fetch_array($this->m_aRecords))
		{
			$aRecords[] = $record;
		}

		$output->addData($aRecords);
		return $output;
		
	}
}
?>